const { md5 } = require('./base-crypto.js') ;
const { notNull } = require("./base-type.js");
function getSignStr (data = {} , escapeKey = ["sign"] , join = '') {
	return Object.keys(data).sort().filter(key => notNull(data[key]) && !escapeKey.includes(key) ).map(key => `${key}=${data[key]}`).join('&');
}

function sign ({data , secret , escapeKey , join , secretKey } = {}) {
	let signStr = getSignStr(data, escapeKey , join) ;
	return md5(`${signStr}${join}${secretKey?secretKey+'=':''}${secret}`).toUpperCase() ;
}

function verifySign (config = {}) {
	let {data, escapeKey , secret , join , secretKey} = config ;
	let signStr = config.sign ;
	return !!signStr && sign({data,secret, escapeKey, join , secretKey }) === signStr ;
}

module.exports = {
	getSignStr ,
	sign ,
	verifySign
}